#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
#include "app_config.h"


static const char* TAG = "app_config";



esp_err_t read_wifi_info(app_wifi_info_t* wifi_info)
{
    ESP_LOGI(TAG, "read_wifi_info");
    esp_err_t ret;
    nvs_handle my_handle;
    ret = nvs_open("wifi", NVS_READONLY, &my_handle);
    if (ret != ESP_OK) {
        ESP_LOGI(TAG, "can not find nvs wifi handle");
        wifi_info->status = 0;  
        return ret;
    }

    ret = nvs_get_u8(my_handle, "status", &wifi_info->status);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info no status");
        wifi_info->status = 0;
        return ret;
    }

    size_t required_size;
    nvs_get_str(my_handle, "ssid", NULL, &required_size);

    ret = nvs_get_str(my_handle, "ssid", &wifi_info->ssid, &required_size);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info no ssid");
        return ret;
    }

    nvs_get_str(my_handle, "password", NULL, &required_size);
    ret = nvs_get_str(my_handle, "password", &wifi_info->password, &required_size);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info no password");
        return ret;
    }

    ESP_LOGI(TAG, "Read SSID:%s, PASSWORD:%s, Status:%d", wifi_info->ssid, wifi_info->password, wifi_info->status);
    return ESP_OK;
}

esp_err_t write_wifi_info(const uint8_t* ssid, const uint8_t* password, uint8_t status)
{
    ESP_LOGI(TAG, "write_wifi_info");
    esp_err_t ret;
    nvs_handle my_handle;
    ret = nvs_open("wifi", NVS_READWRITE, &my_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Error (%d) opening NVS handle!", ret);
        return ret;
    }
    ret = nvs_set_u8(my_handle, "status", status);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info write status failed: %d", ret);
        return ret;
    }

    ret = nvs_set_str(my_handle, "ssid", (char*)ssid);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info write ssid failed: %d", ret);
        return ret;
    }

    ret = nvs_set_str(my_handle, "password", (char*)password);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info write password failed: %d", ret);
        return ret;
    }
 
    ESP_LOGI(TAG, "Save wifi info SSID:%s, PASSWORD:%s", ssid, password);
    return ESP_OK;
}

/*
 * @params: status   1: enabled, 0: disabled
 */
esp_err_t set_wifi_info_status(uint8_t status)
{
    ESP_LOGI(TAG, "set wifi info status:%x", status);
    esp_err_t ret;
    nvs_handle my_handle;
    ret = nvs_open("wifi", NVS_READWRITE, &my_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Error (%d) opening NVS handle!", ret);
        return ret;
    }
    ret = nvs_set_u8(my_handle, "status", status);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Wifi info write status failed: %d", ret);
        return ret;
    }
    return ESP_OK;
}

